package com.heima.media.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author : 王苑
 * @Date : Created in 2022年07月29日
 */
public class UserInterceptor implements HandlerInterceptor {
    /**
     * 前置拦截（访问controller方法之前执行）
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        //uri 包含login 则放行
        if (uri.contains("login")){
            return true;
        }
        //1.从网关转发而来的请求，从请求头重获取自媒体用户ID
        String userId = request.getHeader("userId");
        String userName = request.getHeader("userName");
        //2.将信息存入ThreadLocal中
        if (StringUtils.isNotBlank(userId)){
            //2.封装User对象将对象存入ThreadLocal方便后续web-service 取值
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            user.setUserName(userName);
            UserThreadLocalUtil.set(user);
        }
        return true;
    }

    /**
     * 后置拦截（访问controller方法之后执行）
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清理localThread
        UserThreadLocalUtil.remove();
    }
}
